#include "usermana.h"
#include "ui_usermana.h"
#include<QDebug>
#include<QMessageBox>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
#include <QToolBar>
#include <QFile>
#include <QFileDialog>
UserMana::UserMana(QSqlDatabase &d) :
//    QWidget(parent),
    db(d),
    ui(new Ui::UserMana)
{
    ui->setupUi(this);

    //数据库

    d_model=new QSqlTableModel(this,db);
    d_model->setTable("login");
    nowMode=SNameMode;
//    d_model->setEditStrategy(QSqlTableModel::OnManualSubmit);//设置手动提交修改
//    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);//设置不能编辑表格
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);//设置双击后可以编辑
//    d_model->submitAll();
    getAllUsers();

}

UserMana::~UserMana()
{
    db.close();
    delete ui;
}

void UserMana::getAllUsers()
{
    if(!d_model->select()){
        qDebug()<<"连接错误";
    }
    ui->tableView->setModel(d_model);
    // 设置中文表头
        QStringList chineseHeaders;
        chineseHeaders << tr("用户ID") << tr("用户名") << tr("密码")<< tr("头像");
        for (int i = 0; i < chineseHeaders.size(); ++i) {
            d_model->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
        }

        ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}



void UserMana::on_rueBut_clicked()
{
    d_model->submitAll();
    getAllUsers();
}

void UserMana::on_delUserBut_clicked()
{
    // 获取选中的行
    QModelIndexList selectedIndexes = ui->tableView->selectionModel()->selectedIndexes();
    if (selectedIndexes.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("请选择要删除的行。"));
        return;
    }

    // 获取选中行的主键值
    QModelIndex index = selectedIndexes.first();
    int id = d_model->data(d_model->index(index.row(), 0)).toInt();
    qDebug()<<id;
    // 确认删除
    if (QMessageBox::question(this, tr("确认"), tr("确定要删除选中的用户吗？"),
                              QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
        return;
    }

    // 执行删除操作
    if (d_model->removeRow(index.row())) {
        QMessageBox::information(this, tr("成功"), tr("删除成功。"));
    } else {
        QMessageBox::critical(this, tr("错误"), tr("删除失败。"));
    }
    d_model->submitAll();
    getAllUsers();
}
void UserMana::on_addUserBut_clicked()
{
    // 创建一个对话框来输入用户信息
    QDialog addUserDialog(this);
    addUserDialog.setWindowTitle(tr("添加用户"));

    // 创建输入字段
    QFormLayout *formLayout = new QFormLayout;
    QLineEdit *usernameEdit = new QLineEdit;
    QLineEdit *passwordEdit = new QLineEdit;
    passwordEdit->setEchoMode(QLineEdit::Password); // 密码输入框
    QLineEdit *idEdit = new QLineEdit;

    // 添加输入字段到布局
    formLayout->addRow(tr("用户名:"), usernameEdit);
    formLayout->addRow(tr("账号:"), idEdit);
    formLayout->addRow(tr("密码:"), passwordEdit);

    // 创建按钮和布局
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, &QDialogButtonBox::accepted, &addUserDialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &addUserDialog, &QDialog::reject);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(formLayout);
    layout->addWidget(buttonBox);
    addUserDialog.setLayout(layout);

    // 显示对话框并检查结果
    if (addUserDialog.exec() == QDialog::Accepted) {
        QString username = usernameEdit->text();
        QString password = passwordEdit->text();
        QString userid = idEdit->text();

        // 插入新用户到数据库
        QSqlQuery query(db);
        QString sql=QString("INSERT INTO `login` VALUES ('%1', '%2', '%3');").arg(userid).arg(username).arg(password);
        if (query.exec(sql)) {
            QMessageBox::information(this, tr("成功"), tr("用户添加成功。"));
        } else {
            QMessageBox::critical(this, tr("错误"), tr("用户添加失败：") + query.lastError().text());
        }
    }

    getAllUsers(); // 刷新用户列表
    ui->tableView->scrollToBottom();
}
void UserMana::on_findUserBut_clicked()
{
    QString search = ui->searchEdit->text();

    // 根据条件查询用户
    QSqlQueryModel *queryModel = new QSqlQueryModel(this);
    if(nowMode==SIdMode)
        queryModel->setQuery(QString("SELECT * FROM login WHERE S_Id LIKE '%1'")
                             .arg(search), db);
    else if(nowMode==SNameMode)
        queryModel->setQuery(QString("SELECT login.* FROM student LEFT JOIN login ON student.S_Id = login.S_Id WHERE student.S_Name = '%1';")
                             .arg(search), db);
    else if(nowMode==SClassMode)
        queryModel->setQuery(QString("SELECT login.* FROM student LEFT JOIN login ON student.S_Id = login.S_Id WHERE student.S_Class = '%1';")
                             .arg(search), db);
    else if(nowMode==LoginIdMode)
        queryModel->setQuery(QString("SELECT * FROM login WHERE S_Name LIKE '%1';")
                             .arg(search), db);
    if (queryModel->lastError().type() != QSqlError::NoError) {
        qDebug() << "查询错误:" << queryModel->lastError();
        QMessageBox::critical(this, tr("错误"), tr("查询失败：") + queryModel->lastError().text());
        return;
    }

    // 显示查询结果
    ui->tableView->setModel(queryModel);
    QStringList chineseHeaders;
    chineseHeaders << tr("用户ID") << tr("用户名") << tr("密码")<< tr("头像");
    for (int i = 0; i < chineseHeaders.size(); ++i) {
        d_model->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
    }
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

void UserMana::on_imBut_clicked() {
    QString fileName = QFileDialog::getOpenFileName(this, tr("导入用户"), "", tr("CSV Files (*.csv)"));

    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::critical(this, tr("错误"), tr("无法打开文件：") + file.errorString());
            return;
        }

        QTextStream in(&file);
        QSqlQuery query(db);
        query.prepare("INSERT INTO `login` (S_Id, S_Name, S_Passwd) VALUES (:id, :name, :password)");

        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList fields = line.split(',');
            if (fields.size() < 3) continue; // 确保每行有足够的字段

            query.bindValue(":id", fields[0]);
            query.bindValue(":name", fields[1]);
            query.bindValue(":password", fields[2]);

            if (!query.exec()) {
//                QMessageBox::critical(this, tr("错误"), tr("导入失败：") + query.lastError().text());
                break;
            }
            else {
//                QMessageBox::information(this, tr("成功"), tr("用户数据导入成功。"));
            }
        }
        QMessageBox::information(this, tr("成功"), tr("用户数据导入成功。"));
        file.close();
        getAllUsers(); // 刷新用户列表
    }
}
void UserMana::on_outBut_clicked() {
    QString fileName = QFileDialog::getSaveFileName(this, tr("导出用户"), "", tr("CSV Files (*.csv)"));

    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::critical(this, tr("错误"), tr("无法打开文件：") + file.errorString());
            return;
        }

        QTextStream out(&file);
        QSqlQueryModel model;
        model.setQuery("SELECT * FROM login", db);

        for (int row = 0; row < model.rowCount(); ++row) {
            for (int col = 0; col < model.columnCount(); ++col) {
                out << model.data(model.index(row, col)).toString();
                if (col < model.columnCount() - 1)
                    out << ",";
            }
            out << "\n";
        }

        file.close();
        QMessageBox::information(this, tr("成功"), tr("用户数据导出成功。"));
    }
}

void UserMana::on_comboBox_currentTextChanged(const QString &arg1)
{
    if(arg1=="学号/账号"){
        nowMode = SIdMode;
    }
    else if(arg1=="班级"){
        nowMode = SClassMode;
    }
    else if(arg1=="用户名"){
        nowMode = LoginIdMode;
    }
    else if (arg1 == "姓名") {
        nowMode=SNameMode;
    }
}
